package com.gitee.apanlh.util.encode;

import com.gitee.apanlh.util.valid.ValidParam;

/**	
 * 	字符转义工具类
 * 
 * 	@author Pan
 */
public class StrEscapeUtils {
	
	/** XML特殊标识符结束语句	 */
	private static final String XML_TAG_END = ";";
	/** XML标识 */
	private static final String[][] XML_TAGS = {
		{"&nbsp" , 	 " " }, 
		{"&lt"   , 	 "<" }, 
		{"&gt"   , 	 ">" }, 
		{"&amp"  , 	 "&" }, 
		{"&quot" ,   "\""}, 
		{"&apos" , 	 "'" }, 
		{"&times", 	 "×" }, 
		{"&divide",  "÷" }
	};
	
	/**
	 * 	构造函数
	 * 
	 * 	@author Pan
	 */
	private StrEscapeUtils() {
		//	不允许外部实例
		super();
	}
	
	/**
	 * 	解析替换XML转义符
	 * 	
	 * 	@author Pan
	 * 	@param  str XML
	 * 	@return String
	 */
	public static String unescapeXml(String str) {
		if (ValidParam.isEmpty(str)) {
			return str;
		}
		
		StringBuilder replaceBuilder = new StringBuilder(str.length() + 128).append(str);
		//	替换下标
		int nextIndex = 0;
		
		for (;;) {
			String tag = XML_TAGS[nextIndex][0];
			
			int indexOf = replaceBuilder.indexOf(tag);
			int endIndexOf = replaceBuilder.indexOf(XML_TAG_END, indexOf);
			//	如果未找到则继续寻找
			if (indexOf < 0 || endIndexOf < 0) {
				if (nextIndex == (XML_TAGS.length - 1)) {
					break ;
				}
				nextIndex ++;
			} else {
				replaceBuilder.replace(indexOf, endIndexOf + 1, XML_TAGS[nextIndex][1]);
			}
		}
		return replaceBuilder.toString();
	}
}
